package com.gxuwz.zjh.mxbbx.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gxuwz.zjh.mxbbx.entity.Families;
import com.gxuwz.zjh.mxbbx.entity.Family;
import com.gxuwz.zjh.mxbbx.entity.Pay;
import com.gxuwz.zjh.mxbbx.entity.Pays;
import com.gxuwz.zjh.mxbbx.service.IFamiliesService;
import com.gxuwz.zjh.mxbbx.service.IFamilyService;
import com.gxuwz.zjh.mxbbx.service.IPayService;
import com.gxuwz.zjh.mxbbx.service.IPaysService;
import org.apache.ibatis.annotations.Param;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.crypto.Data;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 参合缴费登记记录 前端控制器
 * </p>
 *
 * @author zhangjiahui
 * @since 2021-03-21
 */
@RestController
@RequestMapping("/mxbbx/pays")
public class PaysController {

    @Autowired
    private IPaysService iPaysService;
    @Autowired
    private IPayService iPayService;
    @Autowired
    private IFamiliesService iFamiliesService;

    /**
     * 查询全部信息
     * @param modelAndView
     * @param request
     * @param response
     * @return
     */
    @Pointcut
    @RequestMapping(value = "/findPaysAll")
    public ModelAndView findPaysAll(ModelAndView modelAndView, Page page, Integer pageNumber,
                                   @Param("PaysId") String paysId,
                                        HttpServletRequest request, HttpServletResponse response) {
        // 可以通过 wrapper 进行筛选!!!
        QueryWrapper<Pays> wrapper = new QueryWrapper<>();
        wrapper.orderByAsc("pays_id");
        // 进行模糊查询!!!
        if(paysId != null && paysId != ""){
            wrapper.like("pays_id", paysId);
            request.getSession().setAttribute("paysId", paysId);
        }else {
            request.getSession().setAttribute("paysId", "");
        }
        // Current,页码 + Size,每页条数
        if(pageNumber == null){
            page.setCurrent(1);
        }else {
            page.setCurrent((long)pageNumber);
        }
        // 默认每页6行数据！
        page.setSize(6);
        // 调用分页查询方法！!
        IPage<Pays> paysIPage = iPaysService.selectPaysPage(page, wrapper);
        HttpSession session = request.getSession();
        // 存放一个数组用来让foreach遍历
        int[] pagesList = new int[(int)paysIPage.getPages()];
        for(int i=0; i< (int)paysIPage.getPages(); i++){
            pagesList[i] = i+1;
        }
        session.setAttribute("pagesList", pagesList);
        // 存放page，内有当前页数
        session.setAttribute("page", page);
        System.out.println("总条数"+paysIPage.getTotal());
        System.out.println("总页数"+paysIPage.getPages());
        // 存放总页数
        session.setAttribute("pages", (int)paysIPage.getPages());
        List<Pays> paysList = paysIPage.getRecords();
        System.out.println("paysList = "+paysList);
        modelAndView.addObject("paysList", paysList);
        modelAndView.setViewName("pays/pays_list");
        return modelAndView;
    }


    /**
     * 跳转进入新增界面
     * @param modelAndView
     * @return
     */
    @RequestMapping(value = "/insertPays")
    public ModelAndView insertPays(ModelAndView modelAndView, HttpServletRequest request,
                                   @Param("familyId") String familyId) {
        if(familyId != null){
            // 通过户编号，查询改户的人员和户内信息
            Families families = new Families();
            families.setFamilyId(familyId);
            List<Families> familiesList = iFamiliesService.findFamiliesByFamily(families);
            System.out.println("familiesList = " + familiesList);
            Pays pays = new Pays();
            pays.setFamilyId(familyId);
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy");
            pays.setYear(formatter.format(new Date()));
            System.out.println("old pays = " + pays);
            pays = iPaysService.findPaysByFamily(pays);
            // 获取当年的缴费方案
            Pay pay = new Pay();
            pay.setYear(formatter.format(new Date()));
            pay = iPayService.findPayByYear(pay);
            System.out.println("pay = " + pay);
            // 判断是否存在本年度缴费方案
            if(pay != null){
                modelAndView.addObject("pay", pay);
            }else {
                request.setAttribute("result_pay", "none");
                modelAndView.setViewName("pays/pays_list");
                return modelAndView;
            }

            // 判断是否存在本年度缴费记录，如果不存在则新增一个模板
            if(pays != null){
                // 如果未缴费人员为空，则跳转提示
                if(pays.getFamilyNum() == 0){
                    request.setAttribute("no_person_pay", "none");
                    modelAndView.setViewName("pays/pays_list");
                    return modelAndView;
                }
                System.out.println("new pays = " + pays);
                modelAndView.addObject("pays", pays);
                String[] names1 = pays.getFamilyNoName().split(",");
                modelAndView.addObject("familiesList", familiesList);
                modelAndView.addObject("names1", names1);
            }else {
                Pays pays1 = new Pays();
                String paysId = familyId + pay.getYear();
                pays1.setPaysId(paysId);
                pays1.setFamilyId(familyId);
                pays1.setNowName(null);
                pays1.setFamilyName(null);
                String familyNoName = "";
                for(int i=0; i<familiesList.size(); i++){
                    familyNoName += familiesList.get(i).getName() + ",";
                }
                pays1.setFamilyNoName(familyNoName);
                pays1.setFamilyNum(familiesList.size());
                pays1.setMoney(0);
                pays1.setMoneys(0);
                pays1.setYear(pay.getYear());
                SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
                pays1.setTime(formatter1.format(new Date()));
                iPaysService.addPays(pays1);
                request.setAttribute("familyId", familyId);
                request.setAttribute("pay_none", "none");
                modelAndView.setViewName("family/family_list");
                return modelAndView;
            }
        }
        modelAndView.setViewName("pays/pays_insert");
        return modelAndView;
    }

    /**
     * 添加信息
     * @param modelAndView
     * @return
     */
    @RequestMapping(value = "/addPays")
    public ModelAndView addPays(ModelAndView modelAndView, Pays pays, HttpServletRequest request,
                                @Param("checkNames") String[] checkNames,
                                @Param("checkMoney") String checkMoney) {
        // 得到当前缴费的人员名称，进行处理
        String checkName = "";
        String noName = pays.getFamilyNoName();
        for(int i=0; i<checkNames.length; i++){
            checkName += checkNames[i] + ",";
            noName = noName.replace(checkNames[i] + ",", "");
        }
        System.out.println("checkName = " + checkName);
        pays.setNowName(checkName);
        String name = pays.getFamilyName() + checkName;

        System.out.println("name = " + name);
        System.out.println("noName = " + noName);
        pays.setFamilyName(name);
        pays.setFamilyNoName(noName);

        // 重新统计已缴费人数
        if(noName.equals(null) || noName.equals("")){
            pays.setFamilyNum(0);
            pays.setFamilyNoName(null);
        }else {
            String[] noNames = noName.split(",");
            pays.setFamilyNum(noNames.length);
        }
        System.out.println("pays.noName = " + pays.getFamilyNum());


        //计算当前的缴费金额
        int money = Integer.valueOf(checkMoney);
        pays.setMoney(money);
        System.out.println("当前的缴费金额 = " + money);
        // 计算当年总共的缴费金额
        pays.setMoneys(pays.getMoney() + pays.getMoneys());
        System.out.println("当年总共的缴费金额 = " + pays.getMoneys());

        Pays Pays1 = iPaysService.findPaysById(pays);
        try {
            if(Pays1 == null){
                iPaysService.addPays(pays);
                request.setAttribute("result1", "addTrue");
            }else {
                iPaysService.updatePaysById(pays);
                request.setAttribute("result2", "editTrue");
            }
        }catch (Exception e){
            request.setAttribute("result1", "addFalse");
        }
        modelAndView.setViewName("pays/pays_list");
        return modelAndView;
    }

    /**
     * 跳转进入修改界面
     * @param modelAndView
     * @return
     */
    @RequestMapping(value = "/updatePays")
    public ModelAndView updatePays(ModelAndView modelAndView, String paysId) {
        Pays pays = new Pays();
        pays.setPaysId(paysId);
        Pays pays1 = iPaysService.findPaysById(pays);
        modelAndView.addObject("pays", pays1);
        modelAndView.setViewName("pays/pays_update");
        return modelAndView;
    }

    /**
     * 修改信息
     * @param modelAndView
     * @return
     */
    @RequestMapping(value = "/editPays")
    public ModelAndView editPays(ModelAndView modelAndView, Pays pays, HttpServletRequest request,
                                 @Param("time") String time) throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
        String time1 = null;
        if(time != null && time != ""){
            Date time2 = formatter.parse(time);
            time1 =formatter.format(time2);
        }
        pays.setTime(time1);
        iPaysService.updatePaysById(pays);
        request.setAttribute("result2", "editTrue");
        modelAndView.setViewName("pays/pays_list");
        return modelAndView;
    }

    /**
     * 删除信息
     * @return
     */
    @RequestMapping(value = "/deletePaysById")
    public ModelAndView deletePaysById(ModelAndView modelAndView, HttpServletRequest request, String paysId) {
        Pays pays = new Pays();
        pays.setPaysId(paysId);
        iPaysService.deletePaysById(pays);
        request.setAttribute("result3", "deleteTrue");
        modelAndView.setViewName("pays/pays_list");
        return modelAndView;
    }

}
